package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.ArticleVisitStreamMess;
import com.heima.utils.common.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Resource
    ApArticleMapper apArticleMapper;
    @Autowired
    AdminFeign adminFeign;
//    @Autowired
//    MongoTemplate mongoTemplate;


    @Override
    public void computeHotArticle() {
//        获取五天前的时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,-5);
        Date date = instance.getTime();

//        获取不同频道的文章列表
        List<ApArticle> allChannel = apArticleMapper.getArticleListLast5Days(date);
//        获取热点文章
        List<HotArticleVo> hotArticles = computeHotArticle(allChannel);
//        缓存热点文章到redis
        cacheHotArticles(hotArticles);
    }

    @Override
    public void updateApArticle(ArticleVisitStreamMess mess) {
//        更新行为数据到数据库
        ApArticle apArticle = new ApArticle();
        apArticle.setId(mess.getArticleId());
        apArticle.setLikes(apArticle.getLikes()+ (int) mess.getLike());
        apArticle.setComment(apArticle.getComment()+ (int) mess.getComment());
        apArticle.setCollection(apArticle.getCollection()+ (int) mess.getCollect());
        apArticle.setViews(apArticle.getViews()+ (int) mess.getView());
        apArticleMapper.updateById(apArticle);
        Integer score = calcuScore(apArticle);
//        更新热点文章队列
        updateHotArticle(apArticle,score);

    }

    private void updateHotArticle(ApArticle apArticle, Integer score) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
//        处理推荐频道
        String jsonStr1 = valueOperations.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
        List<HotArticleVo> voListAll = JSON.parseArray(jsonStr1, HotArticleVo.class);
        handlerList(voListAll,apArticle,score);
//        处理对应频道
        String jsonStr2 = valueOperations.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());
        List<HotArticleVo> voListChannel = JSON.parseArray(jsonStr2, HotArticleVo.class);
        handlerList(voListChannel,apArticle,score);

    }

    /**
     * 检查相应热点队列，进行更新或替换
     * @param voList
     * @param apArticle
     * @param score
     */
    private void handlerList(List<HotArticleVo> voList,ApArticle apArticle, Integer score) {
        boolean flag = true;
        if (voList == null){
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle,hotArticleVo);
            hotArticleVo.setScore(score);
            voList.add(hotArticleVo);
            cacheHotArticles(voList);
            return;
        }
        for (HotArticleVo hotArticleVo : voList) {
            if (hotArticleVo.getId().equals(apArticle.getId())) {
                hotArticleVo.setScore(score);
                flag = false;
            }
        }
        if (flag){
            Optional<HotArticleVo> min = voList.stream().min(Comparator.comparing(HotArticleVo::getScore));
            if (min.get().getScore() < score){
                HotArticleVo hotArticleVo = new HotArticleVo();
                BeanUtils.copyProperties(apArticle,hotArticleVo);
                hotArticleVo.setScore(score);
                voList.add(hotArticleVo);
                voList = voList.stream().sorted(Comparator.comparing(HotArticleVo::getScore)).limit(30).collect(Collectors.toList());
                cacheHotArticles(voList);
            }
        }
    }

    /**
     * 缓存热点文章到redis
     * @param hotArticles
     */
    private void cacheHotArticles(List<HotArticleVo> hotArticles) {
//        获取频道列表
        ResponseResult<List<AdChannel>> responseResult = adminFeign.selectChannels();
        if (responseResult.getCode() != 0){
            log.error("computeHotArticle 远程调用adminFeign获取频道列表失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        List<Integer> channelIDList = responseResult.getData().stream().map(AdChannel::getId).collect(Collectors.toList());
//        遍历频道列表
        channelIDList.stream().forEach(channelID -> {
//            分别将各个频道的热点文章缓存
            List<HotArticleVo> hotArticleVos = hotArticles.stream()
                    .filter(hotArticleVo -> hotArticleVo.getChannelId().equals(channelID))
                    .collect(Collectors.toList());
            sortAndCache(hotArticleVos,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+channelID);
        });
//        总数据缓存
        sortAndCache(hotArticles,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 将热点文章列表排序、截取、缓存
     * @param hotArticleVos
     * @param key
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos,String key) {
        List<HotArticleVo> collect = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30).collect(Collectors.toList());
        redisTemplate.opsForValue().append(key, JSON.toJSONString(collect));
    }

    /**
     * 获取热点文章集合
     * @param allChannel
     * @return
     */
    private List<HotArticleVo> computeHotArticle(List<ApArticle> allChannel) {
        List<HotArticleVo> collect = allChannel.stream().map(apArticle -> {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle, hotArticleVo);
            Integer score = calcuScore(apArticle);
            hotArticleVo.setScore(score);
            return hotArticleVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 计算分值
     * @param apArticle
     * @return
     */
    private Integer calcuScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getViews() != null){
            score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        if (apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
//        if (new Date().getDate() == apArticle.getPublishTime().getDate()){
//            score = score * 3;
//        }
        if (DateUtils.dateToString(new Date()).equals(DateUtils.dateToString(apArticle.getPublishTime()))){
            score = score * 3;
        }
        return score;
    }
}
